const app = getApp()
import util from '../../../utils/util'
import {
  GetEventHandle,
  UpdateMessageOne,
  GetGriderVollege,
  CheckEventIsseu,
  GetEventCatList,
  GetEventDetail,
  GetWarninglist,
  GetIsseuMembers,
  UpSolut
} from '../../../config/api'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    chuli: '',
    type: '', // 下级处理判断
    cat_id: '',
    id: '',
    ucid: '',
    // status: '', // 事件处理状态
    detail: '',

    solut: '', // 解决类型id
    event_index: '',
    eventArr: [], // 上报类型数组
    level_index: '',
    levelArr: ['红色', '黄色'],
    imgs: [],
    count: 0,
    compressImgsSizeArr: [],
    grider_storge: {
      // id: 9,
      // pid:8,
      // name: '王群',
      // vollege_id: 6,
      // town_id: 5
    }, // 网格员缓存信息
    content: '',

    showView: true, // 显示弹窗
    showEventView: true, // 显示事件类型弹窗
    event_type_index: '',
    event_typeArr: [], // 事件类型
    event_cat_index:'',
    isShowNamePopup: false, // 是否显示姓名弹出
    allName: [], // 所有当事人
    uid: '', // 当事人id
    u_name: '', // 当事人名称
    uc_name: '', // 事件类型
    handle_uid: wx.getStorageSync('grider').id,
    handle_name: wx.getStorageSync('grider').name,
    role: wx.getStorageSync('grider').authorize,
    event_level: '',
    event_level_index: 0,
    eventLevelArr: [{
        id: 1,
        title: '普通事件'
      },
      {
        id: 2,
        title: '重点事件'
      }
    ],
    isHideSubmit: true,
    over:0,
    helper: '', // 接收人id
    helper_name: '', // 接收人姓名
    receiverArr: '', // 协助人数组
    name: '', // 协助人搜索名称
    isShowReceiver: '', // 协助人弹层显示
    allCheck: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('options', options)
    let adminInfo = wx.getStorageSync('adminInfo')
    let grider_storge = wx.getStorageSync('grider')
    let handleShow=options.show || 0
    console.log(handleShow)
    this.setData({
      helper: grider_storge.id,
      chuli: options.chuli,
      id: options.id,
      handleShow:handleShow,
      //  status: options.status,
      type: options.type,
      grider_storge: grider_storge, // 正式打开,网格员测试注释 
    })
    this.getGrider();

    this.updateMessageOne() // 修改最新消息状态
    this.checkEventIsseu(); // 调用是否处理过事件
    this.getWarninglist();
    this.getEventType(); // 获取事件类型
    this.getDetail();
    this.getEventHandle()
  },

  updateMessageOne() { // 修改最新消息状态
    util.apiRequest(UpdateMessageOne, {
      id: this.data.id
    }, null).then(r => {
      console.log('修改消息状态：', r)
    })
  },

  getDetail() {
    let that = this;
    util.apiRequest(GetEventDetail, {
      id: this.data.id
    }, null).then(r => {
      console.log(r)
      that.setData({
        detail: r.data.data,
        cat_id: r.data.data.cat_id,
        uid: r.data.data.uid,
        u_name: r.data.data.u_name,
        uc_name: r.data.data.uc_name,
        ucid: r.data.data.ucid,
      })
    })
  },

  checkEventIsseu() { // 判断事件是否处理过
    let that = this;
    let params = {
      id: that.data.grider_storge.id,
      event_id: that.data.id
    }
    util.apiRequest(CheckEventIsseu, params, null).then(r => {
      console.log('是否处理：', r)
      if (that.data.type == 'xiaji' || r.data == 1 || that.data.chuli == 'no') {
        that.setData({
          isHideSubmit: true
        })
      } else {
        that.setData({
          isHideSubmit: false
        })
      }
    })
  },

  getEventHandle() {
    let that = this;
    util.apiRequest(GetEventHandle, null, null).then(r => {
      console.log('事件类型：', r)
      that.setData({
        eventArr: r.data.data
      })
    })
  },
  getGrider: function() {
    let that = this;
    util.apiRequest('/api/GriderProgramApi/getAllGrider', {vollege_id:app.globalData.vollege_id}, null).then(r => {
      console.log('事件3类型：', r)
      that.setData({
        AllGrider: r.data.data
      })
    })

  },
  bindHandleEvent:function(e){
    console.log('事件ss等级：', e.detail.value)
    let uname = this.data.AllGrider[e.detail.value].name
    let uid = this.data.AllGrider[e.detail.value].id
    let authorize = this.data.AllGrider[e.detail.value].authorize
    console.log(uname,uid)

    this.setData({
      handle_name:uname,
      role:authorize,
      event_index: e.detail.value,

      handle_uid:uid,
    })
  },
  radioChange:function(e){
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    this.setData({
      over: e.detail.value,

    })
  },
  bindChangeEventLevel: function(e) {
    console.log('事件等级：', e.detail.value)
    let event_level = this.data.eventLevelArr[e.detail.value]
    this.setData({
      event_level_index: e.detail.value,
      event_level
    })
  },

  getEventType() {
    let that = this;
    util.apiRequest(GetEventCatList, {
      vollege_id: app.globalData.vollege_id
    }).then(r => {
      console.log('事件类型：', r)
      that.setData({
        event_typeArr: r.data.data
      })
    })
  },

  onShowEventPopup() { // 显示事件类型弹层
    this.setData({
      showEventView: false
    })
  },

  onSelectEvent(e) { // 点击选择事件类型
    let event_type_index = e.currentTarget.dataset.event_type_index;
    console.log('事件名称：', this.data.event_typeArr[event_type_index].title)
    console.log('选择事件类型id：', this.data.event_typeArr[event_type_index].id)
    this.setData({
      showEventView: true,
      event_type_index: event_type_index,
      uc_name: this.data.event_typeArr[event_type_index].title,
      ucid: this.data.event_typeArr[event_type_index].id
    })
  },

  onSearchName(e) { // 输入搜索当事人
    console.log(e)
    let name = e.detail.value;
    console.log('name', name)
    if (name != '') {
      this.setData({
        isShowNamePopup: true
      })
      util.apiRequest(GetIsseuMembers, {
        id: this.data.grider_storge.id,
        name: name,
        vollege_id: app.globalData.vollege_id
      }, null).then(r => {
        console.log('搜索：', r)
        this.setData({
          allName: r.data.data
        })
      })
    } else {
      this.setData({
        tname: '',
        isShowNamePopup: false
      })
    }
  },

  onConfirmName(e) { // 点击确认当事人
    console.log('选择姓名', e)
    let uid = e.currentTarget.dataset.id;
    let u_name = e.currentTarget.dataset.name;
    this.setData({
      uid,
      u_name,
      isShowNamePopup: false
    })
  },

  // 预览事件内容图片
  previewAttach: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index);
    let imgs = that.data.detail.attach;
    // console.log('imgs', that.data.Imgs);
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  // 预览事件处理图片
  previewReplyImg: function(e) {
    console.log('预览处理图片e:', e)
    let that = this;
    var index = e.currentTarget.dataset.index;
    var pindex = e.currentTarget.dataset.pindex;

    console.log('aa预览index', index);

    let imgs = this.data.detail.handle_log[pindex].attach

    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  bindChangeEvent: function(e) {
    console.log('处理类型：', e.detail.value)
    let solut = this.data.eventArr[e.detail.value].id
    if (solut == 21) {
      this.getGriderVollege() // 调用协助人数据
    }
    this.setData({
      event_index: e.detail.value,
      solut,
    })
  },

  // bindChangeLevel(e) {
  //   console.log('预警类型：', e.detail.value)
  //   this.setData({
  //     level_index: e.detail.value
  //   })
  // },

  inputContent(e) {
    this.setData({
      content: e.detail.value
    })
  },

  getWarninglist() {
    let that = this;
    util.apiRequest(GetWarninglist, {
      vollege_id: app.globalData.vollege_id
    }).then(r => {
      console.log('预警：', r)
      that.setData({
        levelArr: r.data.data
      })
    })
  },

  onShowChuli() { // 显示我要处理弹层
    this.setData({
      showView: false
    })
  },

  close: function() { // 关闭弹窗
    let that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },

  onSelectReceiver() { // 选择协助人

    this.setData({
      isShowReceiver: true
    })
  },


  checkboxChange(e) { // 选择
    console.log('选择协助人携带value值为：', e.detail.value)
    let namesString = e.detail.value.toString()
    const items = this.data.receiverArr
    const values = e.detail.value

    if (items.length == values.length) { // 选中/取消全选按钮
      this.setData({
        allCheck: true
      })
    } else {
      this.setData({
        allCheck: false
      })
    }

    let idArr = []
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].isChecked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].name === values[j]) {
          idArr.push(items[i].id)
          items[i].isChecked = true
        }
      }
    }

    console.log()

    console.log('已选idArr', idArr)
    let idArrStr = idArr.toString()

    this.setData({
      receiverArr: items,
      helper: idArrStr,
      helper_name: namesString
    })
  },

  checkAll() { // 全选协助人
    let that = this;
    let receiverArr = that.data.receiverArr;
    let idArr = []
    let nameArr = []

    this.setData({
      allCheck: !this.data.allCheck
    })

    for (let i = 0; i < receiverArr.length; ++i) {
      if (this.data.allCheck) {
        receiverArr[i].isChecked = true
        idArr.push(receiverArr[i].id)
        nameArr.push(receiverArr[i].name)
      } else {
        receiverArr[i].isChecked = false
      }
    }

    console.log('全选idArr', idArr)
    let idArrStr = idArr.toString()
    let nameArrStr = nameArr.toString()

    that.setData({
      helper: idArrStr,
      helper_name: nameArrStr,
      receiverArr
    })
  },

  confirmName() { // 确认选择协助人
    this.setData({
      isShowReceiver: false
    })
  },

  getGriderVollege() { // 获取协助人
    let that = this;
    util.apiRequest(GetGriderVollege, {
      name: that.data.name,
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('协助人：', r)
      that.setData({
        receiverArr: r.data.data
      })
    })
  },

  formSubmit() { // 处理提交
    let that = this;
    if (!this.data.ucid) {
      // wx.showModal({
      //   content: '请选择事件类型',
      //   showCancel: false
      // })
      // return;
    }

    let content = this.data.content.replace(/(^\s*)|(\s*$)/g, "");
    if (!content) {
      wx.showModal({
        showCancel: false,
        content: '请填写内容',
      })
      return;
    }

    if (this.data.solut == 1) {
      var params = {
        event_level: this.data.eventLevelArr[this.data.event_level_index].id, // 事件等级
        nick_name: this.data.grider_storge.nick_name,
        ucid: this.data.ucid,
        uid: this.data.uid,
        u_name: this.data.u_name,
        event_id: this.data.id,
        handle_uid: this.data.handle_uid,
        handle_name: this.data.handle_name,
        content: this.data.content,
        attach: this.data.imgs,
        role: this.data.role,
        over:this.data.over,   
        solut: this.data.solut,
      }
    } else {
      var params = {
        event_level: this.data.eventLevelArr[this.data.event_level_index].id, // 事件等级
        nick_name: this.data.grider_storge.nick_name,
        ucid: this.data.ucid,
        uid: this.data.detail.uid,
        u_name: this.data.detail.u_name,
        event_id: this.data.id,
        role: this.data.role,
        over:this.data.over,   

        handle_uid: this.data.handle_uid,
        handle_name: this.data.handle_name,
        content: this.data.content,
        attach: this.data.imgs,
        solut: this.data.solut,
        helper: this.data.helper
      }
    }

    console.log('参数：', params)

    util.apiRequest(UpSolut, params).then(r => {
      console.log('提交后：', r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              console.log('cat_idaa:', that.data.cat_id)
              wx.redirectTo({
                url: "/pages/grid/griderEventList/griderEventList?cat_id=2"
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })

  },

  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },


  // 预览图片
  previewImg: function(e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  }

})